package com.yzh.booksystem.dao;

import com.yzh.booksystem.entity.Book;
import com.yzh.booksystem.entity.User;
import com.yzh.booksystem.utils.Utils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

public class AddBookDao {
    QueryRunner queryRunner = new QueryRunner(Utils.getDataSource());//获取数据源对象来获取连接对象
    //查询添加的图书是否存在
    public boolean queryBook(Book book) throws SQLException {
        String sql = "select * from book where id = ?";
        Book book1= (Book) queryRunner.query(sql, new BeanHandler<>(Book.class), book.getId());//只要id存在就一直错误，无法添加
        if (book1 != null) {
            return true;
        } else {
            return false;
        }

    }
    public boolean addBook(Book book) throws SQLException {
        String sql = "insert into book (id, bookname, price, address, isbn) values (?,?,?,?,?)";
        //数组类型要为Object类型，里面的数据类型混合
        //book为Book类对象，非静态，不可类名直接调用
        Object[] parames = {book.getId(), book.getBookname(), book.getPrice(), book.getAddress(),
                book.getIsbn()};
        int num = queryRunner.update(sql, parames);//queryrunner.update ()的返回值为int类型，// 代表了这个SQL语句对数据库所做的更改的行数，如果返回值为0，表示没有更改任何行。
        if (num > 0) {    //其实这里就是判断添加进去数据没有，在service层又判断一下
            return true;
        } else {
            return false;
        }
    }

//    public List<Book> check_total_books() throws SQLException {
//        String sql = "select * from book";
//        List<Book> listBooks = (List<Book>) queryRunner.query(sql, new BeanListHandler(Book.class));
//        if (listBooks != null) {
//            return listBooks;
//        } else {
//            return null;
//        }
//    }
    public List<Book> check_total_books() throws SQLException {
        QueryRunner queryRunner = new QueryRunner(Utils.getDataSource());
        String sql = "select *from book";
        List<Book> listBooks = (List<Book>) queryRunner.query(sql, new BeanListHandler<>(Book.class));
        if (listBooks != null) {
            return listBooks;
        } else {
            return null;
        }
    }
}
